from rest_framework.serializers import ModelSerializer

from ERP_system.utils.get_inventory import Get_inventory
from purchase_info.models import PurchaseModel,PurchaseItemModel
from rest_framework import serializers
from goods_info .models import  *

#采购项目的序列化器
class PurchaseItemSerializer(ModelSerializer):
    class Meta:
        model=PurchaseItemModel
        fields='__all__'

class PurchaseSerializer(ModelSerializer):
    item_list=PurchaseItemSerializer(many=True,write_only=True)

    #采购订单中要展示的商品信息
    goods_info=serializers.SerializerMethodField(read_only=True)
    class Meta:
        model=PurchaseModel
        fields='__all__'

    def get_goods_info(self,obj):
        '''
        商品信息由商品1 商品规格 ，商品2 商品规格
        :param obj:
        :return:
        '''
        if obj.item_list.all():
            result=[]
            for item in obj.item_list.all():
                result.append(item.name+(item.specification if item.specification else ''))
            return  ','.join(result)
        return ''

    def create(self, validated_data):
       item_list=validated_data.pop('item_list')
       purchase=PurchaseModel.objects.create(**validated_data)
       for item in item_list:
           pim=PurchaseItemModel.objects.create(purchase=purchase,**item)
           goods=item.get('goods')
           pim.name=goods.name
           pim.specification=goods.specification
           pim.number_code=goods.number_code
       return purchase

    def update(self, instance, validated_data):
       if instance.status!='0':
           raise ConnectionError('采购订单已经生效不能修改')
       item_list=validated_data.pop('item_list')
       old_list=instance.item_list.all()
       if old_list.exist():
           instance.item_list.all().delete()
       for item in item_list:
           PurchaseItemModel.objects.create(purchase=instance

                                            , **item)
       return super(PurchaseSerializer,self).update(instance=instance,validated_data=validated_data)

#选择商品列表的序列化器
class ChoiceGoodsSerializer(serializers.Serializer):
    number_code=serializers.CharField(label='货品编号',required=True)
    keyword=serializers.CharField(label='货品搜索关键字，名称，型号，规格，颜色',write_only=True)
    category_id=serializers.IntegerField(label='货品类别ID',required=False)
    warehouse_id=serializers.IntegerField('仓库ID',required=True)

    id=serializers.IntegerField(label='货品id',read_only=True)
    name=serializers.CharField(label='货品名称',read_only=True)
    category__name=serializers.CharField(label='货品名称',read_only=True)
    specification=serializers.CharField(label='货品规格',read_only=True)
    model_number=serializers.CharField(label='货品型号',read_only=True)
    color=serializers.CharField(label='货品颜色',read_only=True)
    units__basic_name=serializers.CharField(label='货品单位',read_only=True)
    cur_inventory=serializers.CharField(label='当前库存',read_only=True)


# 用于查询单个采购订单的序列化器, 主要目的是为了查看采购单详情
class PurchaseGetSerializer(serializers.ModelSerializer):
    """
    仅仅用于查询单个采购订单的序列化器
    """
    item_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = PurchaseModel
        fields = '__all__'

    def get_item_list(self, obj):
        result = []  # 返回的列表，列表中是多个字典
        if obj.item_list.all().exists():
            for item in obj.item_list.all():  # 得到每一个 PurchaseItemModel
                # 一部分信息来自于 GoodsModel货品表， 一部分来自PurchaseItemModel
                # 字典中的内容：货品id，货品编号，名称，规格，型号，颜色，单位，库存， 采购数量，采购单价，采购金额，采购备注
                item_dict = {}
                goods = GoodsModel.objects.get(id=item.goods.id)
                item_dict['goods'] = goods.id
                item_dict['name'] = goods.name
                item_dict['number_code'] = goods.number_code
                item_dict['specification'] = goods.specification
                item_dict['model_number'] = goods.model_number
                item_dict['color'] = goods.color
                item_dict['units'] = goods.units.basic_name
                item_dict['cur_inventory'] = Get_inventory(goods.id)
                item_dict['purchase_count'] = item.purchase_count
                item_dict['purchase_price'] = item.purchase_price
                item_dict['purchase_money'] = item.purchase_money
                item_dict['remark'] = item.remark
                result.append(item_dict)

        return result





